package com.maserb.monitor.web.jw_question;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.maserb.monitor.common.*;
import com.maserb.monitor.entity.JwRegistrationEntity;
import com.maserb.monitor.entity.jwQuestion.*;
import com.maserb.monitor.service.common.JwRegistrationService;
import com.maserb.monitor.service.jwQuestion.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.thymeleaf.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

//问卷调查接口
@RestController
@RequestMapping("/schoolQuestionApp")
public class JwQuestionAppController {

    @Autowired
    private JwQuestionService service;

    @Autowired
    private JwQuestionUserService questionUserService;

    @Autowired
    private JwQuestionItemUserService questionItemUserService;

    @Autowired
    private JwQuestionOptionUserService questionOptionUserService;

    @Autowired
    private JwQuestionItemService jwQuestionItemService;

    @Autowired
    private JwQuestionOptionService jwQuestionOptionService;

    @Autowired
    private JwRegistrationService registrationService;

    //根据用户名获取问卷调查列表(问卷调查)
    @RequestMapping("/doList")
    @ResponseBody
    public PageResponseResult<JwQuestionEntity> doListUser(PageRequestParam page, final String userName,final String schoolId) {
        System.out.println("----------------------------------------------------------");
        System.out.println("----------------------------------------------------------");
        System.out.println("----------------------------------------------------------");
        System.out.println("page:"+page.toString());
        System.out.println("userName:"+userName);
        Sort.Order codeOrder = new Sort.Order(Sort.Direction.DESC, "createTime");
        List<Sort.Order> orderList = new ArrayList<Sort.Order>();
        orderList.add(codeOrder);
        Sort sort = new Sort(orderList);
        return AjaxUtils.processPage(page,sort, new Func_T1<PageRequest, Page<JwQuestionEntity>>() {
            @Override
            public Page<JwQuestionEntity> invoke(PageRequest var1) throws Exception {
                Page<JwQuestionEntity> page = service.findAll(var1,schoolId);
                List <JwQuestionUserEntity> list = questionUserService.findByUserName(userName);
                if(page.getContent()!=null){
                    for(JwQuestionEntity a:page.getContent()){
                        a.setStatus("1");
                        if(null!=list){
                            for(JwQuestionUserEntity jue : list){
                                if(a.getId().equals(jue.getQuestionId())){
                                    a.setStatus("2");
                                }
                            }
                        }
                        a.setItems(null);
                    }
                }
                return page;
            }
        });
    }

    //根据用户名获取已完成的问卷调查
    @RequestMapping("/doListFinished")
    @ResponseBody
    public PageResponseResult<JwQuestionUserEntity> doListFinished(PageRequestParam page, final String userName) {
        Sort.Order codeOrder = new Sort.Order(Sort.Direction.DESC, "createTime");
        List<Sort.Order> orderList = new ArrayList<Sort.Order>();
        orderList.add(codeOrder);
        Sort sort = new Sort(orderList);
        return AjaxUtils.processPage(page, sort,new Func_T1<PageRequest, Page<JwQuestionUserEntity>>() {
            @Override
            public Page<JwQuestionUserEntity> invoke(PageRequest var1) throws Exception {
                Page <JwQuestionUserEntity> page = questionUserService.findAllByUserName(var1,userName);
                return page;
            }
        });
    }


    //  根据问卷id和用户名获取已完成的问卷信息
    @RequestMapping("/doGetFinished")
    @ResponseBody
    public AjaxResult<JwQuestionEntity> doGetFinished(String id,String userName) {
        return AjaxUtils.process(new Func_T<JwQuestionEntity>() {
            @Override
            public JwQuestionEntity invoke() throws Exception {
                List <JwQuestionUserEntity> list = questionUserService.findByQuestionIdAndUserName(id,userName);
                if(list==null){
                    return null;
                }
                JwQuestionUserEntity userEntity = list.get(0);
                String jwQuestionUserId = userEntity.getId();
                List<JwQuestionItemUserEntity>itemUserList=questionItemUserService.findByQuestionUserId(jwQuestionUserId);
                List<JwQuestionOptionUserEntity>optionUserList=questionOptionUserService.findByQuestionUserId(jwQuestionUserId);
                Map<String,String> itemMap = new<String,String> HashMap();
                for(JwQuestionItemUserEntity itemUser : itemUserList){
                    if("3".equals(itemUser.getType())){
                        itemMap.put(itemUser.getQuestionItemId(),itemUser.getQuestionValue());
                    }
                }
                StringBuilder optionUserStr = new StringBuilder();
                for(JwQuestionOptionUserEntity optionUser:optionUserList){
                    optionUserStr.append(optionUser.getQuestionOptionId()+",");
                }
                JwQuestionEntity entity = service.findOne(id);
                for(JwQuestionItemEntity item : entity.getItems()){
                    if(itemMap.containsKey(item.getId())){
                        item.setDescription(itemMap.get(item.getId()));
                    }
                    for(JwQuestionOptionEntity option :item.getOptions()){
                        if(optionUserStr.indexOf(option.getId())!=-1){
                            option.setIsSelected(1);
                        }
                    }
                }
                return entity;
            }
        });
    }

    //  根据id获取问卷
    @RequestMapping("/doGet")
    @ResponseBody
    public AjaxResult<JwQuestionEntity> doGet(String id) {
        return AjaxUtils.process(new Func_T<JwQuestionEntity>() {
            @Override
            public JwQuestionEntity invoke() throws Exception {
                JwQuestionEntity entity = service.findOne(id);
                return entity;
            }
        });
    }

    //  启动程序后调用，保存uuid、registrationId（极光推送设备标识id），更新app使用时间;
    @RequestMapping("/doPush")
    @ResponseBody
    public AjaxResult doPush(String uuid,String registrationId) {
        return AjaxUtils.process(new Func_T<String>() {
            @Override
            public String invoke() throws Exception {
                JwRegistrationEntity entity = new JwRegistrationEntity();
                List<JwRegistrationEntity>list = registrationService.findByUuidAndRegistrationId(uuid,registrationId);
                if(null!=list&&list.size()>0){
                    entity = list.get(0);
                }else{
                    entity.setUuid(uuid);
                    entity.setRegistrationId(registrationId);
                    entity.setIsDel("0");
                }
                entity.setCreateTime(CreateTimeUtils.getCreateTime());
                registrationService.save(entity);
                return "success";
            }
        });
    }






    //  手机端评测完成提交
    @RequestMapping("/doSave")
    @ResponseBody
    public AjaxResult doSave(String userName,String id ,String result){
        return AjaxUtils.process(new Func_T<String>() {
            @Override
            public String invoke() throws Exception {
                saveQuestionUser(userName,id,result);
                return "success";
            }
        });
    }
    void saveQuestionUser(String userName,String id ,String result){
        /*测试数据
        String id = "402880416347f847016347ffa9050005";
        String  result ="[{'id':'402880416347f8470163480237b40006','selectedOptionId':'402880416347f84701634802633d0007','selectedIndex':'1','type':'1'},{'id':'402880416347f8470163480380ee0009','selectedOptionId':'402880416347f847016348044d63000b','selectedIndex':'1','type':'1'},{'id':'402880416347f847016348067c85000e','selectedOptionId':'402880416347f84701634806d2dc0010,402880416347f847016348071a840011','selectedIndex':'1','type':'2'},{'id':'402880416347f847016348080abd0013','selectedOptionId':'402880416347f84701634808a1fe0015','selectedIndex':'1','type':'1'},{'content':'哈哈哈姐姐家','id':'4028804163c4628e0163c46de8fe0000','type':'3'}]";*/
        /*uuid = "F18F29E6-92BA-4B86-99AA-F8CF13786319";
        id = "402880416347f847016347ffa9050005";
        result ="[{'content':'','mainId':'2c90816764b15f910164b17083080001','id':'402880416347f847016348067c85000e','selectedOptionId':'402880416347f84701634806a1a3000f,402880416347f84701634806d2dc0010','selectedIndex':'1','type':'2'},{'content':'','id':'402880416347e640016347ea45440000','mainId':'2c90816764b15f910164b17083080001','selectedOptionId':'402880416347f847016347f9ade50001','selectedIndex':'1','type':'1'},{'content':'哈哈哈姐姐家','id':'4028804163c4628e0163c46de8fe0000','type':'3','selectedOptionId':''}]";*/
        /*result ="[{'id':'402880416347f847016348067c85000e','selectedOptionId':'402880416347f84701634806a1a3000f,402880416347f84701634806d2dc0010','selectedIndex':'1','type':'1'},{'id':'402880416347e640016347ea45440000','selectedOptionId':'402880416347f847016347f9ade50001','selectedIndex':'1','type':'1'},{'content':'哈哈哈姐姐家','id':'4028804163c4628e0163c46de8fe0000','type':'3'}]";*/
        System.out.println("result:"+result);
        System.out.println("userName:"+userName);
        System.out.println("id:"+id);
        JwQuestionEntity jwQuestionEntity = service.findOne(id);
        try{
            jwQuestionEntity.setCount(jwQuestionEntity.getCount()+1);
            service.save(jwQuestionEntity);
        }catch (Exception e){
            e.printStackTrace();
        }
        JwQuestionUserEntity entity = new JwQuestionUserEntity();
        entity.setQuestionId(id);
        entity.setUserName(userName);
        entity.setCreateTime(CreateTimeUtils.getCreateTime());
        entity.setName(jwQuestionEntity.getName());
        entity.setType(jwQuestionEntity.getType());
        entity.setSchoolId(jwQuestionEntity.getSchoolId());
        questionUserService.save(entity);
        String entityId = entity.getId();
        result = "{'data':"+result+'}';
        JSONObject object = JSONObject.parseObject(result);
        JSONArray array = object.getJSONArray("data");
        for(int i = 0; i < array.size(); i++)
        {
            JSONObject o = array.getJSONObject(i);
            JwQuestionItemUserEntity itemUserEntity = new JwQuestionItemUserEntity();
            String itemId ="";
            if(o.get("id")!=null && !"".equals(o.get("id").toString())){
                itemId = o.get("id").toString();
                itemUserEntity.setQuestionItemId(itemId);
            }
            JwQuestionItemEntity itemEntity = jwQuestionItemService.findOne(itemId);
            if(o.get("type")!=null && !"".equals(o.get("type").toString())){
                itemUserEntity.setType(o.get("type").toString());
            }
            if(null!=itemEntity){
                itemUserEntity.setType(itemEntity.getType());
            }
            if(o.get("content")!=null && !"".equals(o.get("content").toString())){
                itemUserEntity.setQuestionValue(o.get("content").toString());
            }
            itemUserEntity.setQuestionUserId(entityId);
            questionItemUserService.save(itemUserEntity);
            if(o.get("selectedOptionId")!=null && !"".equals(o.get("selectedOptionId").toString()) && o.get("id")!=null && !"".equals(o.get("id").toString())){
                String [] aa = o.get("selectedOptionId").toString().split(",");
                for(String a:aa){
                    if (!StringUtils.isEmptyOrWhitespace(a)) {
                        JwQuestionOptionUserEntity optionUserEntity = new JwQuestionOptionUserEntity();
                        JwQuestionOptionEntity optionEntity = jwQuestionOptionService.findOne(a);
                        optionEntity.setCount(optionEntity.getCount() + 1);
                        jwQuestionOptionService.save(optionEntity);
                        optionUserEntity.setQuestionOptionId(a);
                        optionUserEntity.setQuestionItemId(itemId);
                        optionUserEntity.setQuestionUserId(entityId);
                        questionOptionUserService.save(optionUserEntity);
                    }
                }
            }
        }
    }
}
